<?php
/**
 * 站点管理员管理
 */
namespace logic\site;
class AdminManage{
        
    private $User;  //操作人员对象
    public function __construct(\logic\user\User $callUser){
        $this->User = $callUser;
    }
    
    /**
     * 添加管理员
     */
    public function add($data){
        $checkAccount = D('Admin','site')->find(['account'=>$data['account']]);
        if( $checkAccount ) logicE('账户已经存在');
        if( $data['confirmpwd'] != $data['password'] )  logicE('两次密码不一致');
        $info = $this->User->getInfo();       
      //  if( $info['type'] != 1 ) logicE('您无权限添加管理员'); 
        $check =[            
            'msiteid'    => ['check'=>'must','msg'=> '站点主信息ID不能为空','reg'=>'int'],
            'account'   => ['check'=>'must','msg'=>'登录账号不能为空','reg'=>'account'],
            'password'  => ['check'=>'must','msg'=>'密码不能为空'],
            'truename'  => '',
            'gender'    => ['reg'=>[1,2,3]],
            'mobile'    => ['reg'=>'mobile'],
         //   'roleid'    => ['check'=>'must','msg'=> '角色不能为空','reg'=>'int'],
            'addtime'   => ['val'=> SYS_TIME],
            'edittime'  => ['val'=> SYS_TIME],  
            'email'     => ['reg'=> 'email'],
        ];        
        $save = pVerify($check,$data);       
        $save = pFilter()->replace('site_admin',$save,['truename']); 
        if( !$save['roleid']){
            $save['roleid'] = 2; // 默认的站点超级管理员
        }
        $despassword = self::desPassword($save['password']);
        $save['password'] = $despassword['password'];
        $save['passsalt'] = $despassword['passsalt'];
        $adminId = D('Admin','site')->add($save);
        pFilter()->save('site_admin',$adminId);
        return $adminId;
    }
    
    
    /**
     * 对密码进行加密
     * @param $password 单次md5之后的密码或原始密码
     * @param $passsalt 密码撒盐
     * @param $passwordHasMd5 密码是否已经md5 过
     */
    public static function desPassword($password,$passsalt = '',$passwordHasMd5 = false ){
        $key = 'ko$t4Ko1~0mso';
        if( !$passwordHasMd5 ) $password = md5($password);
        if( !$passsalt ) $passsalt = \core\helper\Tools::rand(6);
        trim($password);
        trim($passsalt);
        return [
            'password'  =>  md5( $password.$passsalt.$key ),
            'passsalt'  => $passsalt
        ];
    }
    
}